using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class RichTextLinkHandle : MonoBehaviour
{
    [SerializeField]
    private TextMeshProUGUI m_TextMeshPro;

    [SerializeField]
    private TextMeshProUGUI m_TextMeshPopup;

    [SerializeField]
    private Image m_PopupBg;

    private Canvas m_Canvas;
    private Camera m_Camera;

    private void Awake()
    {
        m_Canvas = gameObject.GetComponentInParent<Canvas>();

        // Get a reference to the camera if Canvas Render Mode is not ScreenSpace Overlay.
        if (m_Canvas.renderMode == RenderMode.ScreenSpaceOverlay)
            m_Camera = null;
        else
            m_Camera = m_Canvas.worldCamera;
    }

    private void LateUpdate()
    {
        int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, this.m_Camera);
        if (linkIndex == -1)
        {
            this.m_PopupBg.gameObject.SetActive(false);
            return;
        }

        this.m_PopupBg.gameObject.SetActive(true);
        this.m_PopupBg.rectTransform.sizeDelta = this.m_TextMeshPopup.rectTransform.sizeDelta + new Vector2(10f, 0f);
        this.m_TextMeshPopup.text = m_TextMeshPro.textInfo.linkInfo[linkIndex].GetLink();
    }

    public void OnRichTextLinkClick(BaseEventData data)
    {
        var allCameras = Camera.allCameras;
        int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, this.m_Camera);
        if (linkIndex == -1)
            return;

        TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];
        Application.OpenURL(linkInfo.GetLinkID());
    }
}
